import { defineStore } from 'pinia';
import { UserState } from '@/types/store/user';
import { LoginFormData } from '@/types/api/sys/user';
import { localStorage } from '@/utils/storage';
import { login, logout, getUserInfo } from '@/api/sys/user';
import { resetRouter } from '@/router';

const useUserStore = defineStore({
	id: 'user',
	state: (): UserState => ({
		token: localStorage.get('token') || '',
		nickname: '',
		id: '',
		avatar: '',
		intro: '',
		roles: [],
		perms: [],
		mode: ""
	}),
	actions: {
		async RESET_STATE() {
			this.$reset();
		},
		/**
		 * 登录
		 */
		login(loginData: LoginFormData) {
			const { username, password, code, uuid, mode } = loginData;
			this.mode = mode;//模式
			return new Promise((resolve, reject) => {
				login({
					username: username.trim(),
					password: password,
					grant_type: 'captcha',
					code: code,
					uuid: uuid,
				})
					.then((response) => {
						//console.log(response.data)
						const { token } = response.data;
						//const accessToken = token_type + ' ' + access_token;
						localStorage.set('token', token);
						this.token = token;
						resolve(token);
					})
					.catch((error) => {//登录失败，判断是否是开发模式，如果是开发模式则直接以开发身份登录
						if (mode == "dev") {
							localStorage.set('token', "dev");
							this.token = "dev";
							resolve(this.token);
						} else {//不是开发身份，则登录失败拒绝
							reject(error);
						}
					});

			});
		},
		/**
		 *  获取用户信息（昵称、头像、角色集合、权限集合）
		 */
		getUserInfo(mode: String) {//mode开发模式 dev 开发者模式
			return new Promise((resolve, reject) => {
				if (mode == "dev") {
					this.nickname = "开发者";
					this.avatar = "";
					this.roles = ["dev"];
					this.perms = [];
					resolve(null);
				} else {
					getUserInfo()
						.then(({ data }) => {

							if (!data) {
								return reject('Verification failed, please Login again.');
							}
							var { role, username, avatar, perms } = data;
							var roles = role?role.split(","):[role];
							if (this.mode && this.mode == "dev") {//如果是开发模式，则添加开发者身份角色
								roles = roles.concat(["dev"])
							}
							if (!roles || roles.length <= 0) {
								reject('getUserInfo: roles must be a non-null array!');
							}
							if (!perms) {
								perms = []
							}
							this.nickname = username;
							this.avatar = avatar;
							this.roles = roles;
							this.perms = perms;
							data.roles = roles
							//console.log("登录成功3"+perms )
							resolve(data);
						})
						.catch((error) => {
							reject(error);
						});
				}

			});
		},

		/**
		 *  注销
		 */
		logout() {
			return new Promise((resolve, reject) => {
				//logout().then(() => {
				localStorage.remove('token');
				this.RESET_STATE();
				resetRouter();
				resolve(null);
				//})
				//.catch((error) => {
				//  reject(error);
				// });
			});
		},

		/**
		 * 清除 Token
		 */
		resetToken() {
			return new Promise((resolve) => {
				localStorage.remove('token');
				this.RESET_STATE();
				resolve(null);
			});
		},
	},
});

export default useUserStore;
